package com.ruoyi.client.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.client.domain.HousekeepingPayment;
import com.ruoyi.client.service.ShoppingService;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.recycle.domain.*;
import com.ruoyi.recycle.dto.*;
import com.ruoyi.recycle.dto.deppon.request.JsonRootBean;
import com.ruoyi.recycle.dto.deppon.response.SynchronousDeBangStatus;
import com.ruoyi.recycle.mapper.SysTypeConfigMapper;
import com.ruoyi.recycle.service.*;
import com.ruoyi.recycle.vo.ClientServeOrderVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.json.JSONObject;
import org.springframework.beans.BeanUtils;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.Map;

@RestController
@RequestMapping("/shopping")
@Api(tags = "客户端小程序逛街相关")
public class ShoppingController {

    @Resource
    private IIntegralCommodityService integralCommodityService;
    @Resource
    private IIntegralOrderService integralOrderService;
    @Resource
    private IRecycleOrderService recycleOrderService;
    @Resource
    private IConsultManagementService consultManagementService;
    @Resource
    private ICommentManagementService commentManagementService;
    @Resource
    private SysTypeConfigMapper sysTypeConfigMapper;
    @Resource
    private CouponService couponService;
    @Resource
    private ShoppingService shoppingService;
    @Resource
    private IIntegralCommodityEvaluateService integralCommodityEvaluateService;

    /**
     * 获取回收商品详细信息
     * Int id
     *
     * @return
     */
    @GetMapping("/selectAllIntegralCommodity/{id}")
    @ApiOperation("获取积分商品详细信息")
    public AjaxResult selectAllIntegralCommodity(@PathVariable(value = "id", required = true) Integer id) {
        return integralCommodityService.selectAllIntegralCommodity(id);
    }

    @GetMapping("/selectCommodityList")
    @ApiOperation("获取积分商品列表")
    public AjaxResult commodityList() {
        final LambdaQueryWrapper<IntegralCommodity> wrapper = Wrappers.lambdaQuery();
        return AjaxResult.success(integralCommodityService.list(wrapper.orderByDesc(IntegralCommodity::getCreatedTime))).
                put("integralCommodityType", sysTypeConfigMapper.selectList(new LambdaQueryWrapper<SysTypeConfig>().eq(SysTypeConfig::getType, "积分商品分类")));
    }


    /**
     * 获取回收商品详细信息
     */
    @GetMapping(value = "/integralCommodity/{id}")
    @ApiOperation("获取回收商品详细信息")
    @ApiImplicitParam(name = "id", value = "id", dataType = "Long")
    public AjaxResult selectRecycleCommodityById(@PathVariable("id") Long id) {
        return AjaxResult.success(integralCommodityService.getById(id));
    }


    @ApiOperation(value = "加入购物袋")
    @PostMapping("/pocket")
    public AjaxResult pocket(@RequestBody PocketReq pocketReq) {
        return shoppingService.pocket(pocketReq);
    }

    @PostMapping("/deletePocketItem")
    @ApiOperation(value = "删除购物袋指定商品")
    public AjaxResult deletePocketItem(@RequestBody PocketReq pocketReq) {
        return shoppingService.deletePocketItem(pocketReq);
    }

    @ApiOperation("查询购物袋列表")
    @ApiImplicitParam(name = "userId", value = "用户ID", required = true, dataType = "Long")
    @GetMapping("/pocketList")
    public AjaxResult pocketList(@RequestParam Long userId) {
        return shoppingService.pocketList(userId);
    }

    @ApiOperation("积分商品下单")
    @PostMapping("/pocketCreateOrder")
    public AjaxResult pocketCreateOrder(@RequestBody PocketCreateOrderReq pocketCreateOrderReq) {
        return integralOrderService.pocketCreateOrder(pocketCreateOrderReq);
    }

    @ApiOperation("支付订单")
    @PostMapping("/payment")
    @ApiImplicitParam(name = "Payment", value = "支付订单", dataType = "Payment", required = true)
    public AjaxResult payment(@RequestBody Payment payment) {
        return integralOrderService.payment(payment);
    }

    @ApiOperation("支付订单结算")
    @PostMapping("/paymentEnd")
    @ApiImplicitParam(name = "Payment", value = "支付订单", dataType = "Payment", required = true)
    public AjaxResult paymentEnd(@RequestBody Payment payment) {
        return integralOrderService.paymentEnd(payment);
    }

    @ApiOperation("微信支付回调")
    @PostMapping("/payCallBack")
    public Map<String, String> payCallBack(HttpServletRequest request) {
        return integralOrderService.payCallBack(request);
    }

    @ApiOperation("取消订单")
    @PostMapping("/cancelIntegralOrder")
    public AjaxResult cancelIntegralOrder(@RequestParam String orderNo) {
        return integralOrderService.cancelIntegralOrder(orderNo);
    }

    @ApiOperation("客户提起申请退款")
    @PostMapping("/applicationForDrawback")
    public AjaxResult applicationForDrawback(@RequestParam(value = "id", required = true) Long id,
                                             @RequestParam(value = "remark", required = true) String remark) {
        return integralOrderService.applicationForDrawback(id, remark);
    }

    /**
     *
     * @param clientId
     * @param collectId
     * @param type  0商品  1 门店
     * @return
     */
    @ApiOperation("客户收藏商品")
    @PostMapping("/collect")
    public AjaxResult collect(@RequestParam(value = "clientId", required = true) Integer clientId,
                              @RequestParam(value = "collectId", required = true) Integer collectId,
                              @RequestParam(value = "type", required = true) Integer type) {
        return integralCommodityService.collect(clientId,collectId,type);
    }

    /**
     * @param clientId
     * @param collectId
     * @param type 0商品  1 门店
     * @return
     */
    @ApiOperation("客户取消收藏商品")
    @PostMapping("/cancelCollect")
    public AjaxResult cancelCollect(@RequestParam(value = "clientId", required = true) Integer clientId,
                                    @RequestParam(value = "collectId", required = true) Integer collectId,
                                    @RequestParam(value = "type", required = true) Integer type) {
        return integralCommodityService.cancelCollect(clientId,collectId,type);
    }

    /**
     * 回收订单/家政订单下单
     */
    @ApiOperation("回收/家政服务下单")
    @PostMapping("/addClientServeOrder")
    public AjaxResult addClientServeOrder(@RequestBody ClientServeOrderVO clientServeOrderVO) {
        return recycleOrderService.addClientServeOrder(clientServeOrderVO);
    }

    /**
     * 快递回收订单回调接口
     */
    @ApiOperation("快递回收订单回调接口")
    @PostMapping("/expressageCallback")
    public SynchronousDeBangStatus expressageCallback(@RequestParam MultiValueMap<String, String> formData) {

        return recycleOrderService.expressageCallback(formData);
    }


    /**
     * 分页查询好玩管理列表
     */
    @PostMapping("/consultPageQuery")
    @ApiOperation("分页查询咨询管理列表")
    public AjaxResult consultPageQuery(@RequestBody ConsultManagement consultManagement) {

        return consultManagementService.selectMiniConsultManagementList(consultManagement);
    }

    /**
     * 获取好玩详细信息
     */
    @GetMapping(value = "/consult/{id}")
    @ApiOperation("获取咨询管理详细信息")
    @ApiImplicitParam(name = "id", value = "id", dataType = "Long")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        ConsultManagement consultManagement = consultManagementService.selectConsultManagementById(id);
        consultManagement.setClickRate(consultManagement.getClickRate() + 1);
        consultManagementService.updateById(consultManagement);
        return AjaxResult.success(consultManagementService.selectConsultManagementById(id)).
                put("comment",commentManagementService.list(new LambdaQueryWrapper<CommentManagement>().
                        eq(CommentManagement::getConsultId,id).
                        eq(CommentManagement::getStatus,"1")));
    }


    @PostMapping(value = "/saveConsult")
    @ApiOperation("新增好玩评论管理")
    public AjaxResult saveConsult(@RequestBody CommentManagement commentManagement) {
        commentManagement.setCreatedTime(new Date());
        commentManagement.setStatus("0");
        commentManagement.setCommentTime(new Date());
        commentManagementService.save(commentManagement);
        return AjaxResult.success();
    }

    /**
     * 分页查询积分商品列表-
     */
    @PostMapping("/commodityPageQuery")
    @ApiOperation("分页查询积分商品列表")
    public AjaxResult commodityPageQuery(@RequestBody IntegralCommodityDTO queryDTO) {
        queryDTO.setPageSize(99999);
        final IntegralCommodity factory = new IntegralCommodity();
        if(StringUtils.isBlank(queryDTO.getType())){
            queryDTO.setType(null);
        }
        BeanUtils.copyProperties(queryDTO, factory);
        factory.setCommodityName(null);
        final LambdaQueryWrapper<IntegralCommodity> wrapper = Wrappers.lambdaQuery(factory);
        if (queryDTO.getSearchTimeBegin() != null) {
            wrapper.ge(IntegralCommodity::getCreatedTime, queryDTO.getSearchTimeBegin());
        }
        if (queryDTO.getSearchTimeEnd() != null) {
            wrapper.le(IntegralCommodity::getCreatedTime, queryDTO.getSearchTimeEnd());
        }
        if (queryDTO.getCommodityName() != null) {
            wrapper.like(IntegralCommodity::getCommodityName,queryDTO.getCommodityName());
        }
        wrapper.orderByDesc(IntegralCommodity::getCreatedTime);
        return AjaxResult.success(integralCommodityService.page(new Page<IntegralCommodity>()
                .setCurrent(queryDTO.getCurrentPage())
                .setSize(queryDTO.getPageSize()), wrapper)).
                put("integralCommodityType", sysTypeConfigMapper.selectList(new LambdaQueryWrapper<SysTypeConfig>().eq(SysTypeConfig::getType, "积分商品分类")));
    }

    @PostMapping("/clientGetCoupon")
    @ApiOperation("领取优惠券")
    public AjaxResult clientGetCoupon(@RequestParam(value = "clientId", required = true) Integer clientId,
                                      @RequestParam(value = "couponId", required = true) String couponId) {
        return couponService.clientGetCoupon(clientId,couponId);
    }

    @ApiOperation("取消回收服务订单前置校验是否存在许愿记录")
    @GetMapping("/checkRecycleOrderPrayerRecord/{orderNo}")
    public AjaxResult checkRecycleOrderPrayerRecord(@PathVariable(value = "orderNo",required = true) String orderNo) {
        return shoppingService.checkRecycleOrderPrayerRecord(orderNo);
    }


    @ApiOperation("取消家政服务/回收服务订单")
    @PostMapping("/cancelServiceOrder")
    public AjaxResult cancelServiceOrder(@RequestParam(value = "orderNo", required = true) String orderNo,
                                          @RequestParam(value = "orderType", required = true) Integer orderType) {
        return shoppingService.cancelServiceOrder(orderNo,orderType);
    }

    @PostMapping("/clientNotarizeOrder")
    @ApiOperation("确认收货")
    public AjaxResult clientNotarizeOrderClientNotarizeOrder(@RequestParam(value = "orderNo", required = true) Integer orderNo) {

        IntegralOrder integralOrder = integralOrderService.getById(orderNo);

        if (ObjectUtils.isEmpty(integralOrder)){
            return AjaxResult.error("服务异常，请联系管理员");
        }

        integralOrder.setStatus("已完成");
        integralOrder.setUpdatedTime(new Date());
        integralOrderService.updateById(integralOrder);
        return AjaxResult.success("确认收货成功,祝您生活愉快");
    }

    @PostMapping("/integralCommodityEvaluate")
    @ApiOperation("评价商品")
    public AjaxResult integralCommodityEvaluate(@RequestBody IntegralCommodityEvaluate integralCommodityEvaluate) {

        integralCommodityEvaluate.setCreatedBy(integralCommodityEvaluate.getClientName());
        integralCommodityEvaluate.setCreatedTime(new Date());
        integralCommodityEvaluateService.insertIntegralCommodityEvaluate(integralCommodityEvaluate);
        return AjaxResult.success("感谢您的评价");
    }

    @PostMapping("/launchHousekeepingOrderPayPrepare")
    @ApiOperation("家政服务支付调起")
    public AjaxResult launchHousekeepingOrderPayPrepare(@RequestParam(value = "hkOrderNo") String hkOrderNo) {
        return shoppingService.launchHousekeepingOrderPayPrepare(hkOrderNo);
    }

    @ApiOperation("支付家政服务订单")
    @PostMapping("/housekeepingPayment")
    @ApiImplicitParam(name = "HousekeepingPayment", value = "支付家政服务订单", dataType = "HousekeepingPayment", required = true)
    public AjaxResult housekeepingPayment(@RequestBody HousekeepingPayment payment) {
        return shoppingService.housekeepingPayment(payment);
    }

    @ApiOperation("家政服务支付完成更新数据")
    @PostMapping("/housekeepingPaymentEnd")
    @ApiImplicitParam(name = "HousekeepingPayment", value = "家政服务支付完成更新数据", dataType = "HousekeepingPayment", required = true)
    public AjaxResult housekeepingPaymentEnd(@RequestBody HousekeepingPayment payment) {
        return shoppingService.housekeepingPaymentEnd(payment);
    }

    @ApiOperation("微信支付回调")
    @PostMapping("/housekeepingPayCallBack")
    public Map<String, String> housekeepingPayCallBack(HttpServletRequest request) {
        return shoppingService.housekeepingPayCallBack(request);
    }

    @PostMapping("/wbkTest")
    @ApiOperation("测试")
    public AjaxResult wbkTest(@RequestBody JsonRootBean sendJson) {

        return recycleOrderService.wbkTest(sendJson);
    }

}
